package com.termux.tasker.utils;

import ohos.app.Context;


import com.termux.tasker.Constants;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import ohos.bundle.IBundleManager;
import ohos.bundle.ApplicationInfo;
import ohos.rpc.RemoteException;

public class TermuxAppUtils {
    private static String  PATH_P = "/.termux/termux.properties";
    private static String  PATH_C = "/.config/termux/termux.properties";
    /**
     * Check if Termux app is installed and accessible. This is done by checking if
     * { com.termux.tasker.Constants#TERMUX_PACKAGE} is installed and
     * { com.termux.tasker.Constants#PREFIX_PATH} is a directory and has read and execute
     * permissions. The { com.termux.tasker.Constants#PREFIX_PATH} directory would not exist
     * if termux has not been installed or setup or { com.termux.tasker.Constants#PREFIX_PATH}
     * was deleted by the user.
     *
     * @param context to get error string.
     * @return errmsg if termux package is not installed, disabled or
     * { com.termux.tasker.Constants#PREFIX_PATH} is not a directory, or does not have
     * read or execute permissions, otherwise null.
     */
    public static String checkIfTermuxAppIsInstalledAndAccessible(final Context context) {

        String errmsg = null;

        IBundleManager packageManager = context.getBundleManager();

        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(Constants.TERMUX_PACKAGE, 0, 0);
        } catch (final RemoteException e) {
            applicationInfo = null;
        }
        boolean termuxAppEnabled = (applicationInfo != null && applicationInfo.enabled);

        // If Termux app is not installed or is disabled
        if (!termuxAppEnabled) {
            errmsg = "The Termux app is not installed or is disabled. It is required by the Termux:Tasker plugin app to run plugin commands.\"";
        }
        // If Termux PREFIX_PATH is not a directory or does not have read or execute permissions
        else if (!Constants.PREFIX_DIR.isDirectory() || !Constants.PREFIX_DIR.canRead() || !Constants.PREFIX_DIR.canExecute()) {
            errmsg = "The Termux app $PREFIX directory is not accessible by the Termux:Tasker plugin app. This may be because you have not installed or setup\n" +
                    "                    Termux app or Termux app and Termux:Tasker app both have different APK signatures because you have managed to install both apps from different sources.\n" +
                    "                    It may also be because termux $PREFIX directory \\\"/data/data/com.termux/files/usr\\\" does not exist or does not have read or execute permissions.\"";
        }

        return errmsg;
    }

    /**
     * Get value of termux property in ~/.termux/termux.properties.
     *
     * @param context      for logging.
     * @param property     name.
     * @param defaultValue if property not found.
     *                     .
     * @return property value if it exists, otherwise defaultValue.
     */
    public static String getTermuxProperty(final Context context, final String property, final String defaultValue) {
        File propsFile = new File(Constants.HOME_PATH + PATH_P);
        if (!propsFile.exists())
        { propsFile = new File(Constants.HOME_PATH + PATH_C); }

        Properties props = new Properties();
        try {
            if (propsFile.isFile() && propsFile.canRead()) {
                try (FileInputStream in = new FileInputStream(propsFile)) {
                    props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
                }
            }
        } catch (Exception e) {
            Logger.logStackTrace(context, "Error loading termux.properties", e);
        }

        return props.getProperty(property, defaultValue);
    }

    /**
     * Determines whether {@link Constants#ALLOW_EXTERNAL_APPS_PROPERTY} property is set to "true" in
     * ~/.termux/termux.properties.
     *
     * @param context for logging.
     * @return true if property exists and value is "true", otherwise false.
     */
    public static boolean isAllowExternalApps(final Context context) {
        return getTermuxProperty(context, Constants.ALLOW_EXTERNAL_APPS_PROPERTY, Constants.ALLOW_EXTERNAL_APPS_PROPERTY_DEFAULT_VALUE).equals("true");
    }
}
